package com.hjimi.color;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;

import com.hjimi.api.iminect.ImiDevice;
import com.hjimi.api.iminect.ImiDeviceAttribute;
import com.hjimi.api.iminect.ImiFrameMode;
import com.hjimi.api.iminect.ImiFrameType;
import com.hjimi.api.iminect.ImiNect;

import java.lang.ref.WeakReference;
import java.nio.ByteBuffer;

import static com.hjimi.color.R.id.sv_color_view;

public class CameraActivity extends AppCompatActivity {


    private SurfaceView mColorViewZD;
    private GLPanel     mGLPanelZD;
    private DecodePanel mDecodePanelZD;
    private Surface     mSurfaceZD;

    private Button btn_Exit;

    private boolean bExiting   = false;
    public  boolean bAllowExit = true;

    private ImiDevice          mDeviceZD;
    private MainListener       mainlistenerZD;
    private SimpleViewer       mViewerZD;
    private ImiDeviceAttribute mDeviceAttributeZD = null;

    private static final int DEVICE_OPEN_SUCCESS = 0;
    private static final int DEVICE_OPEN_FALIED  = 1;
    private static final int DEVICE_DISCONNECT   = 2;
    private static final int MSG_EXIT            = 5;

    private ImageView          imageView;
    public  ByteBuffer         frameDataZD;
    public  ImiDevice.ImiFrame nextFrameZD;

    public void setImage(View view) {

        LogPlus.e("------>nextFrameZD： " + (nextFrameZD == null));
        LogPlus.e("------>nextFrameZD： " + (nextFrameZD.getData() == null));
        LogPlus.e("------> nextFrameZD length:" + nextFrameZD.getData().array().length);
        //        // 根据该RGB数组生成位图
        //        Bitmap bitmap2 = MyBitmapFactory.createMyBitmap(nextFrameZD.getData().array(), nextFrameZD.getWidth(), nextFrameZD.getHeight());
        //
        //        imageView.setImageBitmap(bitmap2);
    }

    static class MyHandler extends Handler {
        WeakReference<CameraActivity> mActivity;

        public MyHandler(CameraActivity activity) {
            mActivity = new WeakReference<CameraActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            CameraActivity mainActivity = mActivity.get();
            switch (msg.what) {
                case DEVICE_OPEN_FALIED:
                case DEVICE_DISCONNECT: {
                    mainActivity.showMessageDialog((String) msg.obj);
                    mainActivity.bAllowExit = true;
                    break;
                }
                case DEVICE_OPEN_SUCCESS: {
                    mainActivity.runViewer(mainActivity);
                    mainActivity.bAllowExit = true;
                    break;
                }
                case MSG_EXIT: {

                    mainActivity.Exit();
                    break;
                }
            }
        }
    }

    private MyHandler MainHandler = new MyHandler(this);

    private void showMessageDialog(String errMsg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(errMsg);
        builder.setPositiveButton("quit", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int arg1) {
                dialog.dismiss();
                bExiting = true;
                new Thread(new ExitRunnable()).start();
            }
        });
        builder.show();
    }

    private void runViewer(final CameraActivity mainActivity) {

        mDeviceAttributeZD = mDeviceZD.getAttribute();

        // set frame mode
        ImiFrameMode frameMode = mDeviceZD.getCurrentFrameMode(ImiDevice.ImiStreamType.COLOR);


        //frameMode.setFormat(IMI_PIXEL_FORMAT_IMAGE_RGB24);
       // frameMode.setFormat(com.hjimi.api.iminect.ImiPixelFormat.IMI_PIXEL_FORMAT_IMAGE_H264);


        mDeviceZD.setFrameMode(ImiDevice.ImiStreamType.COLOR, frameMode);
        LogPlus.d("------> Frame mode: " + frameMode.getResolutionX() + ", " + frameMode.getResolutionY());

        mViewerZD = new SimpleViewer(mDeviceZD, ImiFrameType.COLOR, new SimpleViewer.ShowFrameListenners() {
            @Override
            public void showFrame(ByteBuffer frameData, ImiDevice.ImiFrame nextFrame) {
                LogPlus.d("------> 主页绘制数据：" + frameData.toString());
                mainActivity.frameDataZD = frameData;
                mainActivity.nextFrameZD = nextFrame;
            }
        });

        switch (frameMode.getFormat()) {
            case IMI_PIXEL_FORMAT_IMAGE_H264:
                mDecodePanelZD.initDecoder(mSurfaceZD, frameMode.getResolutionX(), frameMode.getResolutionY());
                mViewerZD.setDecodePanel(mDecodePanelZD);
                break;
            default:
                mColorViewZD.setVisibility(View.GONE);
                mGLPanelZD.setVisibility(View.VISIBLE);
                mViewerZD.setGLPanel(mGLPanelZD);
                break;
        }

        ViewGroup.LayoutParams param = mGLPanelZD.getLayoutParams();
        param.width = frameMode.getResolutionX();
        param.height = frameMode.getResolutionY();
        mGLPanelZD.setLayoutParams(param);

        mViewerZD.onStart();

        // start stream
        mDeviceZD.startStream(ImiDevice.ImiStreamType.COLOR.toNative());
    }

    private class MainListener implements ImiDevice.OpenDeviceListener {

        @Override
        public void onOpenDeviceSuccess() {
            LogPlus.e("------> DEVICE_OPEN_SUCCESS");
            MainHandler.sendEmptyMessage(DEVICE_OPEN_SUCCESS);
        }

        @Override
        public void onOpenDeviceFailed(String errorMsg) {
            //open device falied.
            LogPlus.e("------> DEVICE_OPEN_FALIED、");
            MainHandler.sendMessage(MainHandler.obtainMessage(DEVICE_OPEN_FALIED, errorMsg));
        }
    }

    private class OpenDeviceRunnable implements Runnable {

        @Override
        public void run() {
            LogPlus.e("------> 初始化");
            ImiNect.initialize();
            mDeviceZD = ImiDevice.getInstance();
            mainlistenerZD = new MainListener();

            mDeviceZD.open(CameraActivity.this, 0, mainlistenerZD);
            LogPlus.e("------> 打开摄像头完成");
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_color_view);

        mColorViewZD = (SurfaceView) findViewById(R.id.color_view);

        mColorViewZD.getHolder().addCallback(new SurfaceHolder.Callback() {
            @Override
            public void surfaceCreated(SurfaceHolder surfaceHolder) {
                LogPlus.e("------> surfaceCreated");
                mSurfaceZD = surfaceHolder.getSurface();
                mDecodePanelZD = new DecodePanel();
            }

            @Override
            public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
                LogPlus.e("------> surfaceChanged");
            }

            @Override
            public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
                LogPlus.e("------>surfaceDestroyed ");
                mDecodePanelZD.stopDecoder();
            }
        });

        mGLPanelZD = (GLPanel) findViewById(sv_color_view);

        btn_Exit = (Button) findViewById(R.id.button_Exit);
        imageView = (ImageView) findViewById(R.id.imageView);
        btn_Exit.setOnClickListener(new Button.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (bExiting) {
                    Log.d("@@@@@", "EXITING...");
                    return;
                }

                bExiting = true;
                new Thread(new ExitRunnable()).start();
            }
        });

        bAllowExit = false;
        new Thread(new OpenDeviceRunnable()).start();

        LogPlus.e("------> onCreate");
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mViewerZD != null) {
            mViewerZD.onResume();
        }
    }


    private class ExitRunnable implements Runnable {

        @Override
        public void run() {

            while (!bAllowExit) {
                SystemClock.sleep(30);
            }

            if (mViewerZD != null) {
                mViewerZD.onPause();
            }

            //destroy viewer.
            if (mViewerZD != null) {
                mViewerZD.onDestroy();
            }

            if (mDeviceZD != null) {
                mDeviceZD.close();
                mDeviceZD = null;
                ImiDevice.destroy();
            }

            ImiNect.destroy();

            MainHandler.sendEmptyMessage(MSG_EXIT);
        }
    }

    private void Exit() {

        finish();

        android.os.Process.killProcess(android.os.Process.myPid());
    }


}
